<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="1000px"
    top="2vh"
    @close="close"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="制作员工" prop="MakeStaffID">
        <el-select v-model="form.MakeStaffID" style="width: 100%">
          <el-option
            v-for="(item, index) in TaskStaffList"
            :key="index"
            style="width: 100%"
            :label="item.StaffName"
            :value="item.StaffID"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工种" prop="MakeStaffPost">
        <el-select v-model="form.MakeStaffPost" style="width: 100%">
          <el-option
            v-for="(item, index) in TaskStaffPost"
            :key="index"
            style="width: 100%"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提成总额" prop="TichengTotalMoney">
        <el-input
          v-model="form.TichengTotalMoney"
          disabled
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="提成单价">
        <el-input v-model="form.TichengPrice" disabled style="width: 100%" />
      </el-form-item>
      <el-form-item label="完成数量" prop="FinishNum">
        <el-input-number v-model="form.FinishNum" @change="calculate" />
      </el-form-item>
      <el-form-item label="提成比例" prop="TichengRate">
        <el-input
          v-model="form.TichengRate"
          placeholder="请输入提成比例"
          style="width: 100%"
          @input="calculate"
        />
      </el-form-item>
      <el-form-item label="提成金额" prop="TichengMoney">
        <el-input v-model="form.TichengMoney" disabled style="width: 100%" />
      </el-form-item>
      <el-form-item label="详情说明" prop="FinishMemo">
        <div style="width: 100%; height: 100%; border: 1px solid #ccc">
          <Toolbar
            :editor="editorRef"
            style="border-bottom: 1px solid #e8e8e8"
          />
          <Editor
            v-model="form.FinishMemo"
            class="wang-editor-content"
            :default-config="editorConfig"
            style="height: 400px"
            @on-created="handleCreated"
            @mouseover="changeEditor"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button
        :disabled="isExceed"
        type="primary"
        @click="saveTaskSubmitEdit"
      >
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { saveTaskSubmit } from '@/api/storeDetails'
  import '@wangeditor/editor/dist/css/style.css'

  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  export default defineComponent({
    name: 'WorktaskVideoerStatistics',
    components: { Editor, Toolbar },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const editorRef = shallowRef()
      const html = ref('')
      const editorConfig = ref({
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server:
              'https://api.sanjianke.com/common/Upload/upload?file=teamwork&type=image', // 你的服务器地址，注意：当前接口格式特殊与其他vab接口不同，请查看vip文档
            fieldName: 'file',
            allowedFileTypes: ['image/*'],
            mode: 'cors',
            headers: {}, // 如需传递token请写到在这里
          },
        },
      })
      const state = reactive({
        distributeAmount: 0,
        formRef: null,
        TaskStaffList: [],
        isExceed: false,
        TaskStaffPost: [],
        form: {},
        rules: {
          MakeStaffID: [
            { required: true, trigger: 'change', message: '请选择制作员工' },
          ],
          MakeStaffPost: [
            { required: true, trigger: 'change', message: '请选择工种' },
          ],
          TichengRate: [
            { required: true, trigger: 'blur', message: '请输入提成比例' },
          ],
          FinishNum: [
            { required: true, trigger: 'blur', message: '请输入完成数量' },
          ],
          FinishMemo: [
            { required: true, trigger: 'blur', message: '请填写详情说明' },
          ],
        },
        title: '',
        dialogFormVisible: false,
      })
      const handleCreated = (editor) => {
        editorRef.value = editor
        // console.log('isFullScreen', editor.isFullScreen)
      }

      const changeEditor = () => {
        const editor = editorRef.value
        console.log('isFullScreen', editor)
        if (editor.isFullScreen) {
          state.showAttachment = false
        } else {
          state.showAttachment = true
        }
      }

      const showEdit = (
        row,
        flag,
        TaskStaffList,
        distributeAmount,
        TaskStaffPost,
        taskform
      ) => {
        if (!flag) {
          state.title = '添加'
          state.TaskStaffList = TaskStaffList
          state.distributeAmount = distributeAmount
          state.TaskStaffPost = TaskStaffPost
          state.form = Object.assign({}, row)
          state.form.TichengPrice =
            Number(state.form.TichengMoneys) / state.form.WorkTaskNum
        } else {
          state.title = '编辑'
          state.TaskStaffList = TaskStaffList
          state.distributeAmount = distributeAmount
          state.TaskStaffPost = TaskStaffPost
          state.form = Object.assign({}, row)
          state.form.TichengPrice =
            Number(taskform.TichengMoneys) / taskform.WorkTaskNum
        }
        state.form.FinishNum = 1
        console.log(state.form, '????')
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.dialogFormVisible = false
      }
      // 计算比例
      const calculate = () => {
        let molecule = 1
        let denominator = 1
        console.log(
          state.form.TichengRate.split('/')[0],
          state.form.TichengRate.split('/')[1],
          '切割'
        )
        if (state.form.TichengRate.split('/')[0]) {
          molecule = state.form.TichengRate.split('/')[0]
        }
        if (state.form.TichengRate.split('/')[1]) {
          denominator = state.form.TichengRate.split('/')[1]
        }
        // 总金额大于0的时候才有计算 小于零怎么计算都是0
        if (state.form.TichengTotalMoney > 0) {
          console.log(molecule, denominator, '123123')
          state.form.TichengMoney =
            ((state.form.TichengPrice * molecule) / denominator) *
            state.form.FinishNum
          //保留两位小数点
          state.form.TichengMoney = state.form.TichengMoney.toFixed(2)
          console.log(' state.form.TichengMoney', state.form.TichengMoney)
        } else {
          state.form.TichengMoney = 0
        }

        if (
          Number(state.distributeAmount) + Number(state.form.TichengMoney) >
          Number(state.form.TichengTotalMoney)
        ) {
          ElMessage({
            message: '不可添加，添加后将超出总金额',
            type: 'warning',
          })
          state.isExceed = true
        } else {
          ElMessage({
            message: '可以添加',
            type: 'success',
          })
          state.isExceed = false
        }

        console.log(state.form.TichengMoney, '计算')
      }
      // 添加活编辑录入信息
      const saveTaskSubmitEdit = async () => {
        console.log(state.form, 'hahaha')
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await saveTaskSubmit(state.form)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
            state['formRef'].resetFields()
          }
        })
      }

      // const selMake = (row) => {
      //   const Customer = state.TaskStaffList.find(
      //     (item) => item.StaffID == state.form.MakeStaffID
      //   )
      //   state.form.MakeStaffPostName = Customer.StaffPost
      //   console.log(row, 'row')
      // }

      return {
        ...toRefs(state),
        showEdit,
        handleCreated,
        changeEditor,
        editorConfig,
        editorRef,
        close,
        html,
        saveTaskSubmitEdit,
        calculate,
      }
    },
  })
</script>
